package cn.hct.springboot_pro.controller;

import cn.hct.springboot_pro.entity.Item;
import cn.hct.springboot_pro.entity.Orders;
import cn.hct.springboot_pro.entity.User;
import cn.hct.springboot_pro.service.ItemService;
import cn.hct.springboot_pro.service.OrderService;
import cn.hct.springboot_pro.service.UserService;
import org.apache.commons.io.FilenameUtils;
import org.mybatis.logging.Logger;
import org.mybatis.logging.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.ClassUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Controller
@RequestMapping("/Item")
public class ItemController {

    @Autowired
    ItemService itemService;
    @Autowired
    UserService userService;
    @Autowired
    OrderService orderService;

    /*private static  final Logger logger = LoggerFactory.getLogger(ItemController.class);

    // 项目根路径下的目录  -- SpringBoot static 目录相当于是根路径下（SpringBoot 默认）
    public final static String UPLOAD_PATH_PREFIX = "static/images/item";*/

    @RequestMapping("/addItem")
    public String addItem(HttpSession session, Item item, @RequestParam("imageFile") MultipartFile imageFile, HttpServletResponse response) throws IOException {
        //使用UUID给图片重命名，并去掉四个“-”
        String name = UUID.randomUUID().toString().replaceAll("-", "");
        //获取文件的扩展名
        String ext = FilenameUtils.getExtension(imageFile.getOriginalFilename());
        //设置图片上传路径-绝对路径
        String url= "D:\\JavaEE项目作业\\springboot_pro\\springboot_pro\\src\\main\\resources\\static\\images\\item";
        System.out.println(url);
        //以绝对路径保存重名命后的图片
        imageFile.transferTo(new File(url + "/" + name + "." + ext));
        //保存到数据库的图片路径
        String dataPath = name + "." + ext;
        /*获取用户id*/
        int user_id= (int) session.getAttribute("user_id");

        //当前获取时间
        Date d = new Date();
        //设置时间格式
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //把时间转化为String字段
        String publish_time = df.format(d);
        int i = itemService.addItem(item.getItem_name(),user_id,item.getType(),item.getPrice(),item.getIntroduction(),dataPath,publish_time);

        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html; charset=utf-8");
        PrintWriter out = response.getWriter();

        out.print("<script>alert('" + "发布成功，现在转到最新发布页面" + "');window.location.href='/Item/new-publish?type=0';</script>");
        return null;
    }

    @RequestMapping("/new-publish")
    public String newPublish(Model model,Integer type){
        if (type==0){
            List<Item> itemList=itemService.getAllItemOnTime();
            model.addAttribute("itemList",itemList);
            model.addAttribute("typename","最新发布");
            return "user/new-publish";
        }
        if (type==1){
            String typename="图书教材";
            List<Item> itemList = itemService.getItemByType(typename);
            model.addAttribute("itemList",itemList);
            model.addAttribute("typename",typename);
            return "user/new-publish";
        }
        if (type==2){
            String typename="数码电器";
            List<Item> itemList = itemService.getItemByType(typename);
            model.addAttribute("itemList",itemList);
            model.addAttribute("typename",typename);
            return "user/new-publish";
        }
        if (type==3){
            String typename="美妆衣物";
            List<Item> itemList = itemService.getItemByType(typename);
            model.addAttribute("itemList",itemList);
            model.addAttribute("typename",typename);
            return "user/new-publish";
        }
        if (type==4){
            String typename="生活用品";
            List<Item> itemList = itemService.getItemByType(typename);
            model.addAttribute("itemList",itemList);
            model.addAttribute("typename",typename);
            return "user/new-publish";
        }
        if (type==5){
            String typename="票卷小物";
            List<Item> itemList = itemService.getItemByType(typename);
            model.addAttribute("itemList",itemList);
            model.addAttribute("typename",typename);
            return "user/new-publish";
        }
        else{
            String typename="快递跑腿";
            List<Item> itemList = itemService.getItemByType(typename);
            model.addAttribute("itemList",itemList);
            model.addAttribute("typename",typename);
            return "user/new-publish";
        }


    }

    @RequestMapping("/item-news")
    public String itemNews(Model model,Integer item_id,HttpSession session){
        /*商品详情*/
        Item itemNew = itemService.getItemById(item_id);
        model.addAttribute("itemNew",itemNew);
       /* int user_id= (int) session.getAttribute("user_id");*/
        int user_id;
        if (session.getAttribute("user_id")!=null){
           user_id= (int) session.getAttribute("user_id");
        }
        else{
            user_id= (int)session.getAttribute("admin_id");
        }
        /*判断商家*/
        if(itemNew.getUser_id()== user_id){
            Orders ordersNew = orderService.getOrderByItem(item_id);
            if (ordersNew !=null){
                model.addAttribute("bool","1");
                model.addAttribute("ordersNew",ordersNew);
            }
            else {
                model.addAttribute("bool","0");
            }
        }
        /*买主详情*/
        User userNew = userService.getUserById(itemNew.getUser_id());
        model.addAttribute("userNew",userNew);
        return "user/item-news";
    }

    @RequestMapping("goOrder")
    public String order(Model model, Integer item_id){
        Item itemInfo=itemService.getItemById(item_id);
        model.addAttribute("itemInfo",itemInfo);
        return "user/addOrder";
    }

    @RequestMapping("/user-index")
    public String userIndex(Model model){
        String typeBook="图书教材";
        String typeSmart="数码电器";
        String typeCloth="美妆衣物";
        String typeLift="生活用品";
        String typeTicket="票卷小物";
        String typeRun="快递跑腿";

        List<Item> itemOnTime=itemService.getAllItemOnTime();
        List<Item> itemBook = itemService.getItemByType(typeBook);
        List<Item> itemSmart = itemService.getItemByType(typeSmart);
        List<Item> itemCloth = itemService.getItemByType(typeCloth);
        List<Item> itemLift = itemService.getItemByType(typeLift);
        List<Item> itemTicket = itemService.getItemByType(typeTicket);
        List<Item> itemRun = itemService.getItemByType(typeRun);
        model.addAttribute("itemOnTime",itemOnTime);
        model.addAttribute("itemBook",itemBook);
        model.addAttribute("itemSmart",itemSmart);
        model.addAttribute("itemCloth",itemCloth);
        model.addAttribute("itemLift",itemLift);
        model.addAttribute("itemTicket",itemTicket);
        model.addAttribute("itemRun",itemRun);
        return "user/user-index";
    }
    /*搜索 分页*/
    @RequestMapping("/search")
    public String search(Model model, String search,int pageNo){
        List<Item> itemList = itemService.searchLikeItem(search);
        int pageSize=2;
        int count =itemList.size();
        int pangCount=count%pageSize==0?count/pageSize:count/pageSize+1;//页面总数
        int pageMax=pangCount-1;//最大页数
        if(pageNo < 0 ){
            pageNo=0;
        }
        if(pageNo>pageMax){
            pageNo=pageMax;
        }
        List<Item> itemListPage = itemService.searchLikeItemPage(search,pageNo,pageSize);
        model.addAttribute("itemListPage",itemListPage);
        model.addAttribute("search",search);
        model.addAttribute("pageCount",pangCount);
        model.addAttribute("count",count);
        model.addAttribute("pageNo",pageNo);
        model.addAttribute("pageMax",pageMax);
        return "user/search";
    }

    /*跳转更改商品信息页*/
    @RequestMapping("goUpdateItem")
    public String goUpdateItem(Model model, int item_id){
        Item itemNew = itemService.getItemById(item_id);
        model.addAttribute("itemNew",itemNew);
        return "user/updateItem";
    }

    @RequestMapping("/updateItem")
    public String updateItem(Model model, Item item, HttpServletResponse response,String item_image) throws IOException {

        Date d = new Date();
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String publish_time = df.format(d);
        item.setPublish_time(publish_time);
        int i = itemService.updateItem(item);
        if (i!=0){
            response.setCharacterEncoding("UTF-8");
            response.setContentType("text/html; charset=utf-8");
            PrintWriter out = response.getWriter();

            out.print("<script>alert('" + "更改信息成功" + "');window.location.href='/User/user-news';</script>");
            return null;
        }
        else{
            model.addAttribute("message","更改信息失败");
            return "public/message";
        }
    }

    @RequestMapping("/deleteItem")
    public String deleteItem(Model model,int item_id,HttpServletResponse response) throws IOException {
        int i = itemService.deleteItemById(item_id);
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html; charset=utf-8");
        PrintWriter out = response.getWriter();
        if (i!=0){
            out.print("<script>alert('" + "删除商品成功" + "');history.go(-1);';</script>");
            return null;
        }
        else{
            model.addAttribute("message","删除失败，找工作人员维修吧！！！");
            return "public/message";
        }

    }
}